package com.su.dolphin.core.notification;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.su.dolphin.utils.LogUtil;
import com.su.dolphin.utils.NetStatusUtil;
import com.su.dolphin.utils.NetStatusUtil.NetWorkType;

/**
 * 注意这个类是一个Receiver, 需要在Mainfest注册! 网络状态检测类
 * 需要监听网络状态的地方只需要注册一个监听，如果网络有变化会回调网络改变接口，不需要监听的时候需要反注册
 */
public class NetStatusReveiver extends BroadcastReceiver
{
    
    private static ArrayList<NetStatusListener> mListenerList = new ArrayList<NetStatusListener>();
    private static boolean isAvaliable = false;
    private static NetWorkType mFormerNetWorkType;
    
    public static void registerNetworkStatusListener(NetStatusListener listener) {
        if (!mListenerList.contains(listener))
            mListenerList.add(listener);
    }
    
    public static void unregisterNetworkStatusListener(NetStatusListener listener) {
        mListenerList.remove(listener);
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean nextIsAvaliable = NetStatusUtil.isConnected();
        NetWorkType nextNetWorkType = NetStatusUtil.getConnectType();
        LogUtil.i("Old:" + isAvaliable + "<------->" + "New:" + nextIsAvaliable);
        //网络连接变化/ 网络类型变化都会收到通知
        if (isAvaliable != nextIsAvaliable || mFormerNetWorkType != nextNetWorkType) {
            isAvaliable = nextIsAvaliable;
            mFormerNetWorkType = nextNetWorkType;
            for (NetStatusListener listener : mListenerList) {
                listener.onNetStatusChanged(isAvaliable, NetStatusUtil.getConnectType());
            }
            
        }
    }
    
    public interface NetStatusListener
    {
        
        /**
         * 网络状态发生改变回调接口
         * 
         * @param isAvaliable
         *            true：可用，false：不可用
         */
        public void onNetStatusChanged(boolean isAvaliable, NetStatusUtil.NetWorkType state);
    }
    
}
